#include "fsm_msg.h"
#include "string.h"

void fsm_msg_init(fsm_msg_t *msg_ctr, uint8_t *msg_pool, uint32_t msg_pool_size, uint8_t msg_sgl_size)
{
    msg_ctr->msg_pool      = msg_pool;
    msg_ctr->msg_sgl_size  = msg_sgl_size;
    msg_ctr->msg_sum_cnt   = msg_pool_size / msg_sgl_size;
    msg_ctr->msg_rx_cnt    = 0;
    msg_ctr->msg_read_idx  = 0;
    msg_ctr->msg_write_idx = 0;
}

int fsm_msg_write(fsm_msg_t *msg_ctr, uint8_t *pData, uint8_t DatLen)
{
    int ret = 0;

    if (DatLen > msg_ctr->msg_sgl_size)
    {
        DatLen = msg_ctr->msg_sgl_size;
    }
    
    if(msg_ctr->msg_rx_cnt < msg_ctr->msg_sum_cnt)
    {
        msg_ctr->msg_rx_cnt ++;
        memcpy(&msg_ctr->msg_pool[msg_ctr->msg_write_idx * msg_ctr->msg_sgl_size], pData, DatLen);
        
        msg_ctr->msg_write_idx ++;
        if(msg_ctr->msg_write_idx == msg_ctr->msg_sum_cnt)
        {
            msg_ctr->msg_write_idx = 0;
        }

        ret = 1;
    }

    return ret;
}

int fsm_msg_read(fsm_msg_t *msg_ctr, uint8_t *pData)
{
    int ret = 0;

    if(msg_ctr->msg_rx_cnt > 0)
    {
        msg_ctr->msg_rx_cnt --;
        memcpy(pData, &msg_ctr->msg_pool[msg_ctr->msg_read_idx * msg_ctr->msg_sgl_size], msg_ctr->msg_sgl_size);
        
        msg_ctr->msg_read_idx ++;
        if(msg_ctr->msg_read_idx == msg_ctr->msg_sum_cnt)
        {
            msg_ctr->msg_read_idx = 0;
        }

        ret = 1;
    }

    return ret;
}
